/*
 * @Author: liuqiang
 * @Date: 2021-02-20 18:07:08
 * @Last Modified by: liuqiang
 * @Last Modified time: 2021-03-02 15:07:40
 */
const { Sequelize, DataTypes, Op } = require("sequelize");
const { logger } = require("../utils/log");
const { doSqlMiddle } = require("../utils/tool");

const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: "./storage/bill.sqlite",
  logging: (msg) => {
    logger.info(msg);
  },
});

const Bill = sequelize.define("Bill", {
  id: {
    // id 唯一
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV4,
    unique: true,
    primaryKey: true,
  },
  customerNo: {
    // 会员号
    type: DataTypes.INTEGER,
  },
  customerId: {
    // 客户id 唯一
    type: DataTypes.UUID,
    allowNull: false,
  },
  customerName: {
    // 客户姓名
    type: DataTypes.STRING,
    allowNull: false,
  },
  customerPhone: {
    // 客户电话
    type: DataTypes.STRING,
    allowNull: false,
  },
  customerSex: {
    // 客户性别 0 男生 1 女生
    type: DataTypes.NUMBER,
    defaultValue: -1,
  },
  customerCount: {
    // 客户余额
    type: DataTypes.NUMBER,
    allowNull: false,
  },
  customerVip: {
    // vip等级
    type: DataTypes.NUMBER,
  },
  price: {
    // 支付金额
    type: DataTypes.NUMBER,
  },
  remark: {
    // 订单备注
    type: DataTypes.TEXT,
  },
});

// 创建一条订单记录
async function addBill(data) {
  return doSqlMiddle(async () => {
    let bill = await Bill.create(data);
    return bill.toJSON();
  });
}

// 查询数据
async function findBill({
  limit,
  page,
  id,
  customerName,
  customerPhone,
  price,
  customerNo,
  customerId,
} = {}) {
  const query = {
    where: {},
  };
  if (limit) {
    query.limit = limit;
  }
  if (page) {
    query.offset = page * limit;
  }
  if (customerName) {
    query.where.customerName = {
      [Op.like]: `%${customerName}%`, // 模糊匹配姓名
    };
  }
  if (customerPhone) {
    query.where.customerPhone = customerPhone;
  }
  if (id) {
    query.where.id = id;
  }
  if (price) {
    query.where.price = price;
  }
  if (customerNo) {
    query.where.customerNo = customerNo;
  }
  if (customerId) {
    query.where.customerId = customerId;
  }

  if (Object.keys(query.where).length <= 0) {
    delete query.where;
  }

  return doSqlMiddle(async () => {
    let bills = await Bill.findAll(query);
    return bills.map((item) => item.dataValues);
  });
}

// 删除一条数据
function deleteBill(id) {
  return doSqlMiddle(async () => {
    let res = await Bill.destroy({
      where: {
        id: id,
      },
    });
    return res;
  });
}

module.exports = {
  Bill,
  sequelize,
  addBill,
  findBill,
  deleteBill,
};
